<?php
namespace Api\Model;



use Common\Util\ConfigUtils;

class MedicalRecordModel extends BaseModel {

    private static $instance;

    public static function singleton()
    {
        self::$instance === null and self::$instance = new self();
        return self::$instance;
    }

    public function getListByOrder($query,$order_type,$pageno,$pageSize,$user_id){
        if($query){
            if (strtoupper($query) == 'CP'){
                $where['rd.r_corvis_img'] = array('exp', '!= ""');
                $where['rd.l_corvis_img'] = array('exp', '!= ""');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }else{
                $where1['r.name']=array('like', "%$query%");
                $where1['r.user_id']=array('eq',$user_id);
                $where['_complex']=$where1;
                $where['u.name']  = array('like', "%$query%");
                $where['r.processing_results']  = array('like', "%$query%");
                $where['u.hospital']  = array('like',"%$query%");
//              $where['r.native_place']  = array('like',"%$query%");
//              $where['r.past_history']  = array('like',"%$query%");     // 不搜索籍贯、病史
                $where['r.id_number']  = array('like',"%$query%");
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }
        }
        $map['r.is_show']=array('eq',1);
        $map['r.release'] = 1;
        $map['r.visible']='Y';
        $map['rd.status']=1;
        $rows = $this->alias('r')
            ->join('__USER__ u on r.user_id = u.id','Left')
            ->join('__MEDICAL_RECORD_DETAIL__ rd on r.id=rd.record_id')
            ->where($map)
            ->field('r.*')
            ->order(" r. $order_type  DESC")
            ->group("r.id")
            ->limit(($pageno-1)*$pageSize,$pageSize)
            ->select();
        $rows || $rows=[];

        $record_ids=[];
        foreach ($rows as $key=>$row){
            $record_ids[]=$row['id'];
        }
        $rates =[];
        if($record_ids){
            $rates = UserVoteModel::singleton()->getAvgRateByRecordIds($record_ids);
        }
        foreach ($rows as $key=>$row){
            $rows[$key]['eyelid_status']=unserialize($row['eyelid_status']);
            $rows[$key]['past_history']=unserialize($row['past_history']);
            $rows[$key]['create_time'] = date('Y-m-d', strtotime($row['create_time']));
            $rows[$key]['avg_rate']=$rates[$row['id']]?$rates[$row['id']]:0;
            $rows[$key]['vote_count']=UserVoteModel::singleton()->getCountByRecordId($row['id']);
            $rows[$key]['share_image']=$row['share_image']=ConfigUtils::getConfig('SERVER_URL')."index.php?s=/Api/Image/show&record_id=".$row['id'];
            $rows[$key]['new_comment_count_star']=ceil($row['new_comment_count']/2)>=5?5:ceil($row['new_comment_count']/2);
        }
        return $rows;
    }


    public function getListByUserid($user_id,$pageno,$pageSize){
        $where['is_show']=1;
        $where['visible']='Y';
        $where['user_id']=$user_id;
        $rows= $this->where($where)
            ->order("create_time  DESC")
            ->limit(($pageno-1)*$pageSize,$pageSize)
            ->select();
        foreach ($rows as $key=>$val){
            $rows[$key]['canShare']=MedicalRecordDetailModel::singleton()->canShare($val['id']);
        }
        $rows || $rows=[];

        $record_ids=[];
        foreach ($rows as $key=>$row){
            $record_ids[]=$row['id'];
        }
        $rates =[];
        if ($record_ids){
            $rates = UserVoteModel::singleton()->getAvgRateByRecordIds($record_ids);
        }
        foreach ($rows as $key=>$row){
            $rows[$key]['eyelid_status']=unserialize($row['eyelid_status']);
            $rows[$key]['past_history']=unserialize($row['past_history']);
            $rows[$key]['create_time'] = date('Y-m-d', strtotime($row['create_time']));
            $rows[$key]['avg_rate']=$rates[$row['id']]?$rates[$row['id']]:0;
            $rows[$key]['vote_count']=UserVoteModel::singleton()->getCountByRecordId($row['id']);
            $rows[$key]['share_image']=$row['share_image']=ConfigUtils::getConfig('SERVER_URL')."index.php?s=/Api/Image/show&record_id=".$row['id'];
            $rows[$key]['new_comment_count_star']=ceil($row['new_comment_count']/2)>=5?5:ceil($row['new_comment_count']/2);
        }

        return $rows;
    }
    public function getOneById($id){
        $where['id']=$id;
        $row = $this->where($where)->find();
        return $row;
    }

    public function addOrUpdate($id,$data,$user_id){
        $rst = array();
        if($id>0){
            $row = $this->getOneById($id);
            if($row['user_id']==$user_id){
                $info =array();
                $info['age']=$data['age'];
                $info['sex']=$data['sex'];
                $info['marriage_status']=$data['marriage_status'];
                $info['occupation']=$data['occupation'];
                $info['native_place']=$data['native_place'];
                $info['wear_glasses']=$data['wear_glasses'];
                $info['wear_year']=$data['wear_year'];
                $info['stop_wear_week']=$data['stop_wear_week'];
                $info['myopia_year']=$data['myopia_year'];
                $info['optician_year']=$data['optician_year'];
                $info['mirror_od']=$data['mirror_od'];
                $info['mirror_os']=$data['mirror_os'];
                $info['diopte_change']=$data['diopte_change'];
                $info['diopte_change']=$data['diopte_change'];
                $info['eyelid_status']=serialize($data['eyelid_status']);
                $info['past_history']=serialize($data['past_history']);
                $info['patient_appeall']=$data['patient_appeall'];
                $info['processing_results']=$data['processing_results'];
                $info['name']=$data['name'];
                $extra = json_decode($row['extra'], true);
                $extra['basis_check_pic'] = $data['basis_check_pic'] == null  ? '' :$data['basis_check_pic'];
                $info['extra'] = json_encode($extra);
                $res=$this->where(['id'=>$id])->save($info);
                if ($res !== FALSE) {
                    $rst['result']=200;
                    $rst['msg']='修改成功';
                }else{
                    $rst['result']=201;
                    $rst['msg']='修改失败';
                }
            }else{
                $rst['result']=202;
                $rst['msg']='不能修改别人的病历！';
            }

        }else{

            $info =array();
            $info['user_id']=$user_id;
            $info['age']=$data['age'];
            $info['sex']=$data['sex'];
            $info['marriage_status']=$data['marriage_status'];
            $info['occupation']=$data['occupation'];
            $info['native_place']=$data['native_place'];
            $info['wear_glasses']=$data['wear_glasses'];
            $info['wear_year']=$data['wear_year'];
            $info['stop_wear_week']=$data['stop_wear_week'];
            $info['myopia_year']=$data['myopia_year'];
            $info['optician_year']=$data['optician_year'];
            $info['mirror_od']=$data['mirror_od'];
            $info['mirror_os']=$data['mirror_os'];
            $info['diopte_change']=$data['diopte_change'];
            $info['diopte_change']=$data['diopte_change'];
            $info['eyelid_status']=serialize($data['eyelid_status']);
            $info['past_history']=serialize($data['past_history']);
            $info['patient_appeall']=$data['patient_appeall'];
            $info['processing_results']=$data['processing_results'];
            $info['create_time']=date('Y-m-d H:i:s');
            $info['name']=$data['name'];
            $info['release'] = 0;   // 默认未发布
            $extra['basis_check_pic'] = $data['basis_check_pic'] ==null ? '' : $data['basis_check_pic'];
            $info['extra'] = json_encode($extra);
            $info['id_number']=$this->markIdNumber();
            $res=$this->add($info);
            if($res){
                $rst['result']=200;
                $rst['id']=$res;
                $rst['msg']='新增成功';
            }else{
                $rst['result']=201;
                $rst['msg']='新增失败';
            }
        }

        return $rst;
    }

    public function updateData($id, $data){
        $where['id']=$id;
        $this->where($where)->save($data);
    }

    public function markIdNumber(){
        $like_str=date('ymd');
        $where['id_number']=array('LIKE',"$like_str%");
        $data = $this->where($where)->order('id desc')->find();
        if($data){
            $number = substr($data['id_number'],-3);
            $id_number= date('ymd').'-'.$this->autoInc($number);
        }else{
            $id_number= date('ymd').'-001';
        }
        return $id_number;
    }

    function autoInc($num,$step=1){
        $count=count(str_split($num));
        $num_new=intval($num)+$step;
        if($num_new>pow(10,$count-1)){
            return $num_new;
        }
        else{
            return str_pad($num_new,$count,'0',STR_PAD_LEFT);
        }
    }


    public function getMyCollection($user_id,$pageno,$pageSize){

        $record_ids=MedicalRecordCollectModel::singleton()->getRecordIdsByUserId($user_id);
        if($record_ids){
            $where['is_show']=1;
            $where['visible']='Y';
            $where['id']=array('IN',$record_ids);

            $rows= $this->where($where)
                ->order("create_time  DESC")
                ->limit(($pageno-1)*$pageSize,$pageSize)
                ->select();
        }

        $rows || $rows=[];
        $record_ids=[];
        foreach ($rows as $key=>$row){
            $record_ids[]=$row['id'];
        }
        $rates =[];
        if ($record_ids){
            $rates = UserVoteModel::singleton()->getAvgRateByRecordIds($record_ids);
        }
        foreach ($rows as $key=>$row){
            $rows[$key]['avg_rate']=$rates[$row['id']]?$rates[$row['id']]:0;
            $rows[$key]['share_image']=$row['share_image']=ConfigUtils::getConfig('SERVER_URL')."index.php?s=/Api/Image/show&record_id=".$row['id'];
        }

        return $rows;
    }

    //增加阅读数
    public function incReadCount($id){
        $where['id']=$id;
        $this->where($where)->setInc('read_count');
    }

    //增加收藏数
    public function incCollectCount($id){
        $where['id']=$id;
        $this->where($where)->setInc('collection_count');
    }

    // 增加分享数
    public function incShareCount($id){
        $where['id']=$id;
        $this->where($where)->setInc('share_count');
    }

    //减少收藏数
    public function decCollectCount($id){
        $where['id']=$id;
        $this->where($where)->setDec('collection_count');
    }

    // 发布
    public function release($id, $user_id, $status){
        $where['id'] = $id;
        $row = $this->where($where)->find();
        if($row['user_id']==$user_id){
            $this->where($where)->save(['release'=>$status]);
            $rst['result']=200;
            $rst['msg']='操作成功';
        }else{
            $rst['result']=201;
            $rst['msg']='不能操作别人的病历';
        }
        return $rst;
    }

    public function deleteRecord($id,$user_id){
        $where['id']=$id;
        $row = $this->where($where)->find();
        if($row['user_id']==$user_id){
            $this->where($where)->save(['visible'=>'N']);
            $rst['result']=200;
            $rst['msg']='删除成功';
        }else{
            $rst['result']=201;
            $rst['msg']='不能删除自己的病历';
        }

        return $rst;
    }

    // 增加评论数
    public function incNewCommentCount($id){
        $where['id']=$id;
        $this->where($where)->setInc('new_comment_count');
    }

    // 增加评论数
    public function decNewCommentCount($id){
        $where['id']=$id;
        $this->where($where)->setDec('new_comment_count');
    }
}
